package com.leyou.listener;

import com.leyou.common.constants.RocketMQConstants;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * @author: guojy
 * @date: 2020/3/14 17:20
 * @Description: 监听商品上架，删除静态页面
 * @version: 1.0
 */
@Slf4j
@Component
// 参数一：topic,参数二：tag，参数三：组名
@RocketMQMessageListener(topic = RocketMQConstants.TOPIC.ITEM_TOPIC_NAME,
        selectorExpression = RocketMQConstants.TAGS.ITEM_DOWN_TAGS,
        consumerGroup = "ITEM_PAGE_DOWN")
public class ItemDownListener implements RocketMQListener<Long> {

    @Value("${ly.static.itemDir}")
    private String itemDir;

    @Override
    public void onMessage(Long spuId) {
        log.info("[搜索服务]- (商品下架) -接收消息，spuId={}", spuId);
        // 准备删除的文件
        File file  = new File(itemDir,spuId+".html");
        if (!file.exists()) {
            // 如果文件不存在  抛出异常
            throw  new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        boolean delete = file.delete();
        if (!delete){
            // 如果删除失败 抛出异常
            throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
        }
    }
}
